package org.mspring.mlog.web.module.web.connect;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.mspring.mlog.api.connect.qq.oauth.OAuth;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.utils.StringUtils;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * QQ互联
 * 
 * @author Gao Youbo
 * @since 2013年8月7日
 */
@Widget
@RequestMapping("/connect/qq")
public class Web_QQConnect extends Web_AbstractConnectWidget {
    @RequestMapping({ "/", "" })
    public String connect(HttpServletRequest request, HttpServletResponse respones, Model model) {
        return "redirect:" + OAuth.getAuthorizeURL();
    }

    @RequestMapping("/callback")
    public String callback(HttpServletRequest request, HttpServletResponse response, Model model) {
        String code = RequestUtils.getRequestParameterAsString(request, "code");
        String state = RequestUtils.getRequestParameterAsString(request, "state");
        if (StringUtils.isBlank(code) || StringUtils.isBlank(state)) {
            return "skin:/connect/qq/error";
        }
        HttpResponse httpResponse = null;
        String resultString = null;
        try {
            httpResponse = OAuth.getAccessToken(code);
            resultString = EntityUtils.toString(httpResponse.getEntity());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (httpResponse == null || httpResponse.getStatusLine().getStatusCode() != 200) {
            return "skin:/connect/qq/error";
        }
        try {
            Map<String, String> result = OAuth.parseTokenString(resultString);
            String access_token = result.get("access_token").toString();
            String expires_in = result.get("expires_in").toString();
            String refresh_token = result.get("refresh_token").toString();
        } catch (Exception e) {
            // TODO: handle exception
            return "skin:/connect/qq/error";
        }
        return "redirect:/";
    }

}
